package com.cn.fw4j.mvc.servlet.impl;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cn.fw4j.container.impl.GroovyController;
import com.cn.fw4j.container.impl.JavaController;
import com.cn.fw4j.container.impl.Scanning;
import com.cn.fw4j.container.inter.IContainer;
import com.cn.fw4j.mvc.servlet.inter.IDispatcherHandle;
import com.cn.fw4j.mvc.servlet.inter.IServletController;

public class DispatcherHandle implements IDispatcherHandle {
	private final static Logger logger = LoggerFactory.getLogger(DispatcherHandle.class);
	private static String encoding = "UTF-8";
	
	static{
		logger.info("Start DispatcharServlet!!!");
		IContainer ic = new Scanning();
		ic.register(JavaController.getInstance());
		ic.register(GroovyController.getInstance());
		ic.run();
	}
	
	private static String basePath(HttpServletRequest request){
   	 	return request.getContextPath();
    }
    private static String urlPath(HttpServletRequest request){
   	 	String base = basePath(request);
   	 	String url = request.getRequestURI();
   	 	if(!base.equals("/")){
   		 	url = url.replace(base, "");
   	 	}
   	 	return url;
    }
    
    private void run(HttpServletRequest request, HttpServletResponse response,String urlPath){
    	try {
    		response.setCharacterEncoding(encoding);
			request.setCharacterEncoding(encoding);
	    	IServletController javaServlet = new JavaServletController();
	    	IServletController groovyServlet = new GroovyServletController();
	    	javaServlet.controller(request, response, urlPath);
	    	groovyServlet.controller(request, response, urlPath);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
    }

	@Override
	public void get(HttpServletRequest request, HttpServletResponse response) {
		 String urlPath = "GET$"+urlPath(request);
    	 logger.info(urlPath);
    	 run(request, response, urlPath);
    	 
	}

	@Override
	public void post(HttpServletRequest request, HttpServletResponse response) {
		 String urlPath = "POST$"+urlPath(request);
    	 logger.info(urlPath);
    	 run(request, response, urlPath);
		
	}

	@Override
	public void put(HttpServletRequest request, HttpServletResponse response) {
		 String urlPath = "PUT$"+urlPath(request);
    	 logger.info(urlPath);
    	 run(request, response, urlPath);
		
	}

	@Override
	public void delete(HttpServletRequest request, HttpServletResponse response) {
		 String urlPath = "DELETE$"+urlPath(request);
    	 logger.info(urlPath);
    	 run(request, response, urlPath);
	}

}
